#!/bin/bash
sessionid=`iscsiadm -m session | grep $2 | grep $1 | sed 's@\[\(.*\)\] .*@\1@g' | cut -d':' -f2 2>&1 2>/dev/null`
if [ "${sessionId}" == "" ] ; then
    if [ "$3" != "" ] ; then
        iscsiadm -m node --targetname $1 --op=update --name=node.session.auth.authmethod --value=CHAP 2>&1
        iscsiadm -m node --targetname $1 --op=update --name=node.session.auth.username --value=$3 2>&1
        iscsiadm -m node --targetname $1 --op=update --name=node.session.auth.password --value=$4 2>&1
    fi
    output=`iscsiadm --mode node --targetname $1 --portal $2 --login 2>&1`
fi
for i in `iscsiadm -m session --sid $sessionid -P3 2>/dev/null | grep "Lun\|Attached.*disk" | grep -B1 "State:" | sed '$!N;;s/\n/ /' | awk '{print $6"="$7"|device="$11"|"$12"="$13}'`
do
    device_name=`echo $i | awk -F'|' '{print $2}' | cut -d'=' -f2`
    #Get disk size. We have issue in getting disk in first attempt. So we are looping through for 10 times.
    #If in between, we get the disk size then we are breaking the loop.
    counter=0
    while [ $counter -le 10 ];
    do
        output=`iscsiadm -m discovery -t st -p "$2" 2>&1 2>/dev/null`
        #output=`iscsiadm -m session --sid $1`
        disk_size=`fdisk -l /dev/${device_name} 2>/dev/null | grep "Disk /dev/${device_name}" | awk '{print $5}'`
        if [ "$disk_size" != "" ]; then
            break
        fi
        (( counter++ ))
    done
    #disk size check is to avoid "(standard_in) 1: parse error"
    if [ "$disk_size" == "" ]; then
        disk_size=0
    fi
    disk_size_in_GB=`echo "scale=2; $disk_size / 1024 /1024 /1024" | bc`
    lun=`echo $i | awk -F'|' '{print $1}' | sed 's/://'`
    # look for in /dev/disk/by-uuid
    #uuid=`ls -al --time-style="+%Y-%m-%d %H:%M:%S" /dev/disk/by-uuid/* 2>/dev/null | grep ${device_name}$ | awk '{print $8}'`
    ## if not found look for in /dev/disk/by-path
    #if [ "$uuid" == "" ]; then
    uuid=`ls -al --time-style="+%Y-%m-%d %H:%M:%S" /dev/disk/by-path/* 2>/dev/null | grep ${device_name}$ | awk '{print $8}'`
    #fi
    # if not found look for in /dev/disk/by-id
    #if [ "$uuid" == "" ]; then
    #uuid=`ls -al --time-style="+%Y-%m-%d %H:%M:%S" /dev/disk/by-id/* 2>/dev/null | grep ${device_name}$ | awk '{print $8}'`
    #fi
    # if not just return the path
    if [ "$uuid" == "" ]; then
        continue
    fi
    echo "$lun|/dev/${device_name}|${disk_size_in_GB}GB|$uuid"
done